package com.example.demo.controller;

import com.example.demo.payload.DataRequest;
import com.example.demo.payload.DataResponse;
import com.example.demo.utils.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

@RestController
@RequestMapping("/api/mail")
public class MailController {
    @Autowired
    JavaMailSenderImpl javaMailSender;

    @PostMapping("/sendSimpleMail")
    public DataResponse sendSimpleMail(@RequestBody DataRequest dataRequest) {
        String Receiver = dataRequest.getString("email");
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("注册验证码信息");
        Integer code = new Random().nextInt(8999) + 1000;
        message.setText("【智能数据分析系统】您的验证码是 " + code + ",有效时间 5 分钟，请不要泄露验证码给其他人。如非本人操作,请忽略！");
        message.setTo(Receiver);
        message.setFrom("1665587834@qq.com");
        //默认发送方已经配置好了
        javaMailSender.send(message);
        return CommonMethod.getReturnData(200,code,"发送成功");
    }

    @PostMapping("/sendImageMail")
    public DataResponse sendImageMail(@RequestBody DataRequest dataRequest){
        try{
            String imgData= dataRequest.getString("imageData");//获取图片Base64编码
            String to=dataRequest.getString("email");//
            String subject=dataRequest.getString("subject");
            String analyse=dataRequest.getString("analyse");
            // 将Base64编码的图片转换为HTML img标签
            String imgTag = "<img src='data:image/png;base64," + imgData.split(",")[1] + "'/>";
            // 构建邮件正文
            String emailBody = "根据数据绘制的:<br>" + imgTag +"<br>得到的结论是:<br>"+analyse;
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(to);
            helper.setFrom("1665587834@qq.com");
            helper.setSubject(subject);
            helper.setText(emailBody, true); // 第二个参数为true表示启用HTML格式
            javaMailSender.send(mimeMessage);
            return CommonMethod.getReturnMessage(200,"ok");
        }catch(MessagingException e){
            return CommonMethod.getReturnMessage(500, "Failed to send email: " + e.getMessage());
        }

    }
}
